<?php
namespace Tiger\Libs;

/**
 * Tiger 配置管理类
 * @author Stone.Shi 2213152917@qq.com
 */
class Config extends \ArrayObject
{
	/**
	 * 配置
	 */
	protected $config = array();
	
	/**
	 * 配置文件目录
	 */
	protected $config_path = array();

	/**
	 * 当前使用的目录别名
	 */
	protected $dir_alias = null;
	
	/**
	 * 设置配置文件目录
	 * @param $path
	 */
	public function setPath($path ,$alias)
	{
		$_path = realpath($path);	
		//检查是否目录				
		if (!is_dir($_path)) return false;
		//检查是否设置别名
		if (empty($alias)) return false;
		//检查是否加载
		if (isset($this->config_path[$alias])) return false;
		//设置默认加载别名
		if ($this->dir_alias == null)
			$this->dir_alias = $alias;
		
		$this->config_path[$alias] = $path;
		return true;
	}
	/**
	 * 设置当前使用的目录别名
	 */
	public function setUseDirAlias($alias)
	{
		if(isset($this->config_path[$alias]))
		{
			$this->dir_alias = $alias;
			return $this->dir_alias;
		}
		return false;
	}
	
	public function offsetGet($index)
	{
		if (!isset($this->config[$this->dir_alias][$index])) 
			$this->load($index);
		return isset($this->config[$this->dir_alias][$index]) ? $this->config[$this->dir_alias][$index] : false;
	}
	
	public function offsetSet($index, $newval)
	{
		$this->config[$this->dir_alias][$index] = $newval;
	}
	
	public function offsetUnset($index)
	{
		unset($this->config[$this->dir_alias][$index]);
	}
	
	public function offsetExists($index)
	{
		return isset($this->config[$this->dir_alias][$index]);
	}
	
	/**
	 * 加载配置类文件
	 * @param $index
	 */
	protected function load($index)
	{
		if (isset($this->config_path[$this->dir_alias])) 
		{
			$filename = $this->config_path[$this->dir_alias] .'/'. $index . '.php';
			if (is_file($filename)) 
			{
				$retData = include_once $filename;
				if (!empty($retData))
					$this->config[$this->dir_alias][$index] = $retData;
			}
		}
	}
}